<?php
class MigratePagesController extends AppController {
	var $name = 'MigratePages';
	var $uses = array('editable_pages.EditablePage', 'RelatedImage', 'RelatedPage');
	var $helpers = array('Javascript', 'Html');
	
	/**
	 @var $model
	 @brief Thông tin về model, được sử dụng trong trường hợp override thông tin của danh mục
	 */
	var $model = array(
		'plugin'	=>	'categories',
		'name'		=>	'Category'
	);
	/**
	 @var $model
	 @brief Thông tin về model, được sử dụng trong trường hợp override thông tin của danh mục
	 */
	var $models = array(
		'Category'	=>	array(
			'plugin'	=>	'categories',
			'name'		=>	'Category'
		)
	);
	var $relatedPageGroup = "Information";
	
	function beforeFilter() {
		if (!Configure::read('migrating')) {
			exit('Not in migrating mode');
		}
		
		parent::beforeFilter();
		foreach ($this->models as $key => $item) {
			App::import('Model', $item['plugin'].".".$item['name']);
			$this->{$item['name']} = new $item['name']();
		}
		
		$this->set('models', $this->models);
		
		$this->configs = $this->{$this->models['Page']['name']}->loadConfig();
		
		$this->category_root_id = $this->configs['Category']['root_id'];
		
		$this->params['named']['root'] = '';

		$this->set('configs', $this->configs);
	}
	
	function index() {
		//exit('Open exit function on line 48');
		$this->migrate_editable_pages();
		
		//$this->render('dump');
		exit('finished');
	}
	
	function migrate_editable_pages() {
		$records = $this->getPages();
		//debug($records);exit;
		$this->mapIds = array();
		$categories = array(); //alias => id
		
		foreach ($records as $item) {
			// save hotel
			$this->data[$this->models['Page']['name']] = $item['EditablePage'];
			unset($this->data[$this->models['Page']['name']]['id']);
			
			$this->{$this->models['Page']['name']}->create($this->data);
			$this->{$this->models['Page']['name']}->save($this->data);
			
			// get hotel id
			$lastInsertID = $this->{$this->models['Page']['name']}->getLastInsertID();
			$this->mapIds[$item['EditablePage']['id']] = $lastInsertID;
			
			// save to reference category
			# a. Get category id
			if (!isset($categories[$item['Category']['alias']])) {
				$cat_info = $this->{$this->models['Category']['name']}->find('first', array(
					'conditions'	=>	array("{$this->models['Category']['name']}.alias" => $item['Category']['alias']),
					'fields'		=>	array('id'),
					'contain'		=>	array()
				));

				if (isset($cat_info[$this->models['Category']['name']]['id'])) {
					$categories[$item['Category']['alias']] = $cat_info[$this->models['Category']['name']]['id'];
				}
			}

			if (isset($categories[$item['Category']['alias']])) {
				$referenceData[$categories[$item['Category']['alias']]][] = $lastInsertID;
				
				$middle = array(
					'category_id'	=>	$categories[$item['Category']['alias']],
					'page_id'		=>	$lastInsertID
				);
				$this->{$this->middle}->create($middle);
				$this->{$this->middle}->save($middle);
			}
			
			// save related images
			if ($this->configs['RelatedImages']['isActive']) {
				foreach ($item['RelatedImage'] as $image) {
					$image['model'] = $this->models['Page']['name'];
					$image['foreign_key'] = $lastInsertID;
					$this->RelatedImage->set($image);
					$this->RelatedImage->save($image);
				}
			}
		}
		
		// Update Related Pages
		if (!empty($this->configs['RelatedPages'])) {
			foreach ($records as $page) {
				$this->related_pages($page['EditablePage']['id']);
			}
		}
		
		// Update extra fields if exists
		if (count($this->configs['ExtraFields'])) {
			// Tìm kết nối giữa  cũ => mới
			$pairs = $this->{$this->models['Page']['name']}->find('list', array(
				'fields'	=>	array('EditablePage.id', "{$this->models['Page']['name']}.id"),
				'contain'	=>	array(),
				'joins' => array(
					array(
						'table' => 'editable_pages',
						'type' => 'INNER',
						'alias' => 'EditablePage',
						'conditions' => array(
							"EditablePage.alias = {$this->models['Page']['name']}.alias"
						)
					)
				),
			));
			
			list($extraFieldModel, $item) = each($this->configs['ExtraFields']);
			App::import('Model', $extraFieldModel);
			$this->{$extraFieldModel} = ClassRegistry::init($extraFieldModel);
			
			foreach ($pairs as $old => $new) {
				$this->{$extraFieldModel}->updateAll(
					// fields
					array(
						"foreign_id"	=>	$new
					),
					// conditions
					array(
						'foreign_id'	=>	$old
					)
				);
			}
		}
	}
	
	function related_pages($id) {
		// Tìm thông tin related ứng với trang , sử dụng ID
		$options = array(
			'conditions'	=>	array(
				'RelatedReference.foreign_key'	=>	$id,
				'RelatedReference.model'		=>	'EditablePage',
				'RelatedReference.group'		=>	$this->relatedPageGroup
			),
			'contain'		=>	array(),
			'fields'		=>	array(
				'RelatedReference.id', 'RelatedReference.id'
			),
			'order'			=>	"EditablePage.priority asc",
			'joins' => array(
				array(
					'table' => 'editable_pages_categories',
					'type' => 'INNER',
					'alias' => 'ReferenceCategory',
					'conditions' => array(
						"EditablePage.id = ReferenceCategory.page_id"
					)
				),
				array(
					'table' => 'related_pages',
					'type' => 'INNER',
					'alias' => 'RelatedReference',
					'conditions' => array(
						"EditablePage.id = RelatedReference.related_page_foreign_key",
						'RelatedReference.related_page_model'	=>	'EditablePage'
					)
				)
			),
			'limit'	=>	10000
		);

		$related_pages = $this->EditablePage->find('list', $options);

		// Lấy tất cả related_pages
		$e_ids = $this->RelatedPage->find('list', array(
			'fields'	=>	array('related_page_foreign_key', 'related_page_foreign_key'),
			'conditions'	=>	array('id' => $related_pages)
		));
		
		$this->EditablePage->Behaviors->detach('Translate');
		$records = $this->EditablePage->find('all', array(
			'conditions'	=>	array(
				'EditablePage.id'	=>	$e_ids
			)
		));
		
		// Với mỗi trang, lưu vào bảng chính với ngôn ngữ
		$languages = Configure::read('Config.languages');
		foreach ($records as $record) {
			$data[$this->models['Page']['name']] = $record['EditablePage'];
			unset($data[$this->models['Page']['name']]['id']);
			
			foreach ($languages as $langCode => $language) {
				$this->{$this->models['Page']['name']}->locale = $language;
				$this->{$this->models['Page']['name']}->create($data);
				$this->{$this->models['Page']['name']}->save($data);
			}
			
			$this->RelatedPage->updateAll(
				array(
					'related_page_model'	=> "'".$this->models['Page']['name']."'",
					'model' 				=> "'".$this->models['Page']['name']."'",
					'foreign_key'			=>	$this->mapIds[$id],
					'related_page_foreign_key'	=>	$this->{$this->models['Page']['name']}->id
				),
				array(
					'foreign_key'				=>	$id,
					'related_page_foreign_key'	=>	$record['EditablePage']['id']
				)
			);
		}
	}
	
	function getPages() {
		$conditions = array();
		if ($this->category_root_id != null) {
			$category_ids = $this->EditablePage->getChildCatIds(array('root_id' => $this->category_root_id));
			// Load Child Category Id
			if (count($category_ids)) {
				$conditions = array(
					'ReferenceCategory.category_id'	=>	$category_ids
				);
			}
		}

		$extraFields = array();
		
		$limit = 10000;
		
		$order = array("{'EditablePage'}.priority desc");
		$contains = array('RelatedImage');
		
		$options = array(
			'conditions'	=>	$conditions,
			'contain'		=>	$contains,
			'fields'		=>	array_merge(array(
				"EditablePage.id",
				"EditablePage.alias",
				"EditablePage.title",
				"EditablePage.image",
				"EditablePage.description",
				"EditablePage.content",
				"EditablePage.priority",
				"EditablePage.created",
				"EditablePage.modified",
				"Category.name", 
				"Category.alias"),$extraFields),
			'order'			=>	'EditablePage.priority desc',
			'joins' => array(
				array(
					'table' => 'editable_pages_categories',
					'type' => 'INNER',
					'alias' => 'ReferenceCategory',
					'conditions' => array(
						"EditablePage.id = ReferenceCategory.page_id"
					)
				),
				array(
					'table' => 'categories',
					'type' => 'INNER',
					'alias' => 'Category',
					'conditions' => array(
						"Category.id = ReferenceCategory.category_id"
					)
				)
			),
			'limit'	=>	10000
		);
		
		$this->EditablePage->Behaviors->detach('Translate');
		//debug($options);exit;
		$pages = $this->EditablePage->find('all', $options);
		
		//debug($this->paginate['EditablePage']);exit;
		return $pages;
	}
}
?>